/*****************************************************************************************************
 *
 * voltage.cpp
 *
 * Decetects voltage peak.
 *
 *****************************************************************************************************/
// Include Files
 #include "mbed.h"
 #include "voltage.h"
// Set Pins For Function Calls
AnalogIn voltage(p15);
DigitalOut sync_Pulse_Pin(p22);
// Global Variables
float last_Volts = 0;
bool check_0 = false;
/*******************************************************************
* Voltage Monitoring Function
*    This function measures the voltage and caputres the waveform
*    with the maximum to be at 3.3 Volts and having a zero value of
*    1.65 Volts to be able to have both positive and negative part
*    of the sine wave.
*******************************************************************/
float voltage_Monitoring() {
//0.011 is scaling factor to reduce from 150V AC to 1.65 AC
    return ((voltage.read()-1.65)/0.011);
}
/**********************************************************************************************
  *
  * float is_Voltage_at_Peak
  * 
  * Checks to see if the current voltage is the maximum value that is seen by the mBed. Keeps 
  * cycling thru until the maximum voltage is found and then sends a pulse to the slave boards 
  * for them to start counting until they see the peak of the current that they are measuring. 
  *
  **********************************************************************************************/
float is_Voltage_at_Peak(float volts, Timer a) {
    if (volts > last_Volts) {
        check_0 = true;
        last_Volts = volts;
    } else if (check_0 == true) {
        if ( volts < last_Volts) {
            a.start();
            //Send sync pulse;
            sync_Pulse_Pin = true;
            sync_Pulse_Pin = !sync_Pulse_Pin;
            
            return volts;
        } else {
            check_0 = false;
            return false;
        }
    } else {
        check_0 = false;
        return false;
    }
}
/**********************************************************************************************
 *
 * Calculated the RMS voltage of the system.
 *
 **********************************************************************************************/
float calcuate_RMS_Voltage(float peak) {
    return peak/1.414;
}
